/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;
import model.Project;
import session.ProjectFacadeRemote;
import util.Constants;

/**
 *
 * @author Aqua
 */
public class projectController {
     public static ProjectFacadeRemote getProjectFacade() throws NamingException{
        return util.Facade.getProjectFacade();
    }

    /**
     * Get Action Link HTML code to insert into JSP file.
     */
    public static String getActionLink(String id) {
        String edit = "<a onclick=\"doAction(frmIndex, '" + Constants.ADMIN_PAGE_NAME +
                "', '" + Constants.PROJECT_MANAGEMENT_PAGE_NAME + "', '" + Constants.PROJECT_EDIT +
                "', '" + Constants.SHOW_EDIT_PAGE +"', '" + id + "')\">Edit</a>";
        String delete = "<a onclick=\"doAction(frmIndex, '" + Constants.ADMIN_PAGE_NAME +
                "', '" + Constants.PROJECT_MANAGEMENT_PAGE_NAME+ "', '" + Constants.PROJECT_LIST +
                "', '" + Constants.DELETE +"', '" + id + "')\">Delete</a>";
        return edit + delete;
    }

    /**
     * Show all projects on screen.
     */
    public static void showAllProjects(JspWriter out) {
        Controller.log.info("showAllProjects");
        try {
            List<model.Project> projectList = getProjectFacade().findAll();

            /*
             * Show Project List on Screen.
             */
            //Create the title
            out.println("<div id='list-table'>");
            out.println("<div class='row'>");
            out.println("<div class='column-header' style='width: " +
                    Constants.ID_COLUMN_SIZE +";'>ID</div>");
            out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_NAME_COLUMN_SIZE +";'>Name</div>");
            out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_DESCRIPTION_COLUMN_SIZE +";'>Description</div>");
            out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_NAME_COLUMN_SIZE +";'>PM</div>");
            out.println("<div class='column-header' style='width: " +
                    Constants.DATE_COLUMN_SIZE +";'>Started Day</div>");
            out.println("<div class='column-header' style='width: " +
                    Constants.DATE_COLUMN_SIZE +";'>Ended Day</div>");
            out.println("<div class='column-header' style='width: " +
                    Constants.OBJECT_NAME_COLUMN_SIZE +";'>Status</div>");
            out.println("<div class='column-header' style='width: " +
                    Constants.ACTION_COLUMN_SIZE +";'>Action</div>");
            out.println("<div class='clear'></div>");
            out.println("</div>");
            
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
            String startedDay = null;
            String endedDay = null;

            //Show Values
            for(int i = 0; i < projectList.size(); i++) {
                Project node = projectList.get(i);
                if(node.getStartedDate()==null){
                    startedDay = "-";
                }else{
                    startedDay = dateFormat.format(node.getStartedDate());
                }
                if(node.getEndedDate()==null){
                    endedDay = "-";
                }else{
                    endedDay = dateFormat.format(node.getEndedDate());
                }                
                    
                out.println("<div class='row'>");
                out.println("<div class='column' style='width: " +
                        Constants.ID_COLUMN_SIZE +";'>" +
                        node.getProjectID() + "</div>");
                out.println("<div class='column' style='width: " +
                        Constants.OBJECT_NAME_COLUMN_SIZE +";'>" +
                        node.getName() + "</div>");
                out.println("<div class='column' style='width: " +
                        Constants.OBJECT_DESCRIPTION_COLUMN_SIZE +";'>" +
                        node.getDescription() +"</div>");
                out.println("<div class='column' style='width: " +
                        Constants.OBJECT_NAME_COLUMN_SIZE +";'>" +
                        node.getPm().getShortName() +"</div>");
                out.println("<div class='column' style='width: " +
                        Constants.DATE_COLUMN_SIZE +";'>" +
                        startedDay +"</div>");
                out.println("<div class='column' style='width: " +
                        Constants.DATE_COLUMN_SIZE +";'>" +
                        endedDay +"</div>");
                out.println("<div class='column' style='width: " +
                        Constants.OBJECT_NAME_COLUMN_SIZE +";'>" +
                        node.getStatusID().getName() +"</div>");
                out.println("<div class='column' style='width: " +
                        Constants.ACTION_COLUMN_SIZE +";'>" +
                        getActionLink(node.getProjectID()) +"</div>");
                out.println("</div>");
                out.println("<div class='clear'></div>");
            }
            out.println("</div>");

            Controller.log.info("showAllprojects finish.");
        } catch(Exception ex) {
            Controller.log.error("Error showAllprojects: " + ex.getMessage());
        }
    }

    /**
     * Show the page Edit Project on the screen.
     */
    public static void showEditProjectPage(JspWriter out, String id){
    }

    /**
     * Process action with Project Page.
     */
    public static void processAction(HttpServletRequest request) {
        String action = request.getParameter("action");
        String selectedID = request.getParameter("selectedItemID");
        Controller.log.info("projectController.processAction");

        try {
            if(Constants.DELETE.equalsIgnoreCase(action)) {
                //Process DELETE action.
                if((selectedID == null) || "".equals(selectedID)) {
                    //If the selectedID is null, throw an Exception.
                    throw new Exception("No selected id to delete.");
                } else {
                    //Delete selected Project.
                    getProjectFacade().deleteByID(selectedID);

                    Controller.sendMessage(request, "Deleted Project: " + selectedID, false);
                    Controller.log.info("Deleted Project: " + selectedID);
                }

            } else if(Constants.SHOW_EDIT_PAGE.equalsIgnoreCase(action)) {
                //Process SHOW_EDIT_PAGE action.
                if((selectedID == null) || "".equals(selectedID)) {
                    //If the selectedID is null, throw an Exception.
                    throw new Exception("No selected id to edit.");
                } else {
                    //Get value to send back to Edit page.
                    Project project = getProjectFacade().find(selectedID);
                    if(project == null) {
                        throw new Exception("The selected Project not found.");
                    } else {                                                  
                        HttpSession session = request.getSession();
                        
                        Date startedDay = project.getStartedDate();
                        Date endedDay = project.getEndedDate(); 
                        
                        session.setAttribute("projectID", project.getProjectID());
                        session.setAttribute("name", project.getName());
                        session.setAttribute("description", project.getDescription());
                        session.setAttribute("pm", project.getPm().getEmployeeID().toString());
                        if(startedDay != null){
                            session.setAttribute("Sdate", Integer.toString(startedDay.getDate()));
                            session.setAttribute("Smonth", Integer.toString(startedDay.getMonth()+1));
                            session.setAttribute("Syear", Integer.toString(startedDay.getYear()+1900));
                        } else{
                            session.setAttribute("Sdate", null);
                            session.setAttribute("Smonth", null);
                            session.setAttribute("Syear", null);
                        }
                        if(endedDay != null){
                            session.setAttribute("Edate", Integer.toString(endedDay.getDate()));
                            session.setAttribute("Emonth", Integer.toString(endedDay.getMonth()+1));
                            session.setAttribute("Eyear", Integer.toString(endedDay.getYear()+1900));
                        } else{
                            session.setAttribute("Edate", null);
                            session.setAttribute("Emonth", null);
                            session.setAttribute("Eyear", null);
                        }
                        session.setAttribute("status", project.getStatusID().getProjectStatusID());          
                    }
                }

            } else if(Constants.INSERT.equalsIgnoreCase(action)) {
                //Process INSERT action.
                String projectID = request.getParameter("projectID");
                String name = request.getParameter("name");
                String description = request.getParameter("description");
                String pm = request.getParameter("pm");
                String Sdate = request.getParameter("Sdate");
                String Smonth = request.getParameter("Smonth");
                String Syear = request.getParameter("Syear");
                String Edate = request.getParameter("Edate");
                String Emonth = request.getParameter("Emonth");
                String Eyear = request.getParameter("Eyear");
                String status = request.getParameter("status");
                
                Date startedDay = util.StringDate.createDate(Sdate, Smonth, Syear);
                Date endedDay = util.StringDate.createDate(Edate, Emonth, Eyear);
                if(endedDay == null)
                    Controller.log.info("null");
                else
                    controller.Controller.log.info(endedDay.getDate() +"-"+endedDay.getMonth());
                name = util.Unicode.changeToUnicode(name);
                description = util.Unicode.changeToUnicode(description);

                if((projectID == null) || "".equals(projectID)) {
                    //If the ID is null.
                    Controller.sendMessage(request, "Please input ID.", true);
                    throw new Exception("The input ID is null.");
                } else if((name == null) || "".equals(name)) {
                    //If the Name is null.
                    Controller.sendMessage(request, "Please input Name.", true);
                    throw new Exception("The input Name is null.");
                } else if((pm == null) || "".equals(pm)) {
                    //If the pm is null.
                    Controller.sendMessage(request, "Please input PM.", true);
                    throw new Exception("The input PM is null.");
                } else if(startedDay == null) {
                    //If the startedDay is null.
                    Controller.sendMessage(request, "Please input Start Day.", true);
                    throw new Exception("The input Start Day is null.");
                } else if(endedDay == null && status.equalsIgnoreCase("EN")){  
                    //if the ended day is null and status is Ended
                    Controller.sendMessage(request, "The input Ended Day is unaceptable", true);
                    throw new Exception("The input Ended Day is conflicted.");
                } else if(endedDay != null && !status.equalsIgnoreCase("EN")){
                    //if the ended day is not null and status is not Ended
                    Controller.sendMessage(request, "The input Ended Day is unaceptable", true);
                    throw new Exception("The input Ended Day is conflicted.");
                } else if((status == null) || "".equals(status)) {
                    //If the Status is null.
                    Controller.sendMessage(request, "Please input Status.", true);
                    throw new Exception("The input Status is null.");
                } else {
                    ProjectFacadeRemote projectBean = getProjectFacade();
                    model.Employee _pm = util.Facade.getEmployeeFacade().find(Integer.parseInt(pm));
                    model.Projectstatus _status = util.Facade.getProjectStatusFacade().find(status);
                    if(projectBean.find(projectID) != null) {
                        //If the Project id already exists.
                        Controller.sendMessage(request, "The Project ID have already exists,", true);
                        throw new Exception("The Project ID have already exists.");
                    } else {
                        //Insert new Project into DB.
                        Project temp = new Project(projectID, name);
                        temp.setDescription(description);
                        temp.setPm(_pm);
                        temp.setStartedDate(startedDay);
                        temp.setEndedDate(endedDay);
                        temp.setStatusID(_status);
                        projectBean.insert(temp);
                    }
                }

                Controller.sendMessage(request, "Insert Successfully.", false);
                Controller.log.info("Insert Project: " + projectID);

            } else if(Constants.EDIT.equalsIgnoreCase(action)) {
                //Process EDIT action.
                String projectID = request.getParameter("projectID");
                String name = request.getParameter("name");
                String description = request.getParameter("description");
                String pm = request.getParameter("pm");
                String Sdate = request.getParameter("Sdate");
                String Smonth = request.getParameter("Smonth");
                String Syear = request.getParameter("Syear");
                String Edate = request.getParameter("Edate");
                String Emonth = request.getParameter("Emonth");
                String Eyear = request.getParameter("Eyear");
                String status = request.getParameter("status");
                
                Date startedDay = util.StringDate.createDate(Sdate, Smonth, Syear);
                Date endedDay = util.StringDate.createDate(Edate, Emonth, Eyear);
                
                name = util.Unicode.changeToUnicode(name);
                description = util.Unicode.changeToUnicode(description);
            
                if((name == null) || "".equals(name)) {
                    //If the Name is null.
                    Controller.sendMessage(request, "Please input Name.", true);
                    throw new Exception("The input Name is null.");
                } else if(startedDay == null){
                    Controller.sendMessage(request, "Please input Started Day.", true);
                    throw new Exception("The input Started Day is null.");
                } else if(status == null || "".equals(status)){
                    //if the status is null
                   Controller.sendMessage(request, "Please input Status", true); 
                   throw new Exception("The input Status is null.");
                }else if(endedDay == null && status.equalsIgnoreCase("EN")){  
                    //if the ended day is null and status is Ended
                    Controller.sendMessage(request, "The input Ended Day is unaceptable", true);
                    throw new Exception("The input Ended Day is conflicted.");
                } else if(endedDay != null && !status.equalsIgnoreCase("EN")){
                    //if the ended day is not null and status is not Ended
                    Controller.sendMessage(request, "The input Ended Day is unaceptable", true);
                    throw new Exception("The input Ended Day is conflicted.");
                }else {
                    ProjectFacadeRemote projectBean = getProjectFacade();
                    Project project = projectBean.find(projectID);                      
                    model.Employee _pm = util.Facade.getEmployeeFacade().find(Integer.parseInt(pm));
                    model.Projectstatus _status = util.Facade.getProjectStatusFacade().find(status);
                    if(_pm==null){
                        throw new Exception("Cannot found the target PM.");
                    } else if(project == null) {
                        throw new Exception("Cannot found the target Project.");
                    } else {
                        project.setName(name);
                        project.setDescription(description);
                        project.setPm(_pm);
                        project.setStartedDate(startedDay);
                        project.setEndedDate(endedDay);
                        project.setStatusID(_status);
                        projectBean.edit(project);
                        
                    }
                }

                Controller.sendMessage(request, "Save Successfully.", false);
                Controller.log.info("Save Project: " + projectID);
            }
        } catch (Exception ex) {
            Controller.log.error("Error ProjectController.processAction" + ex.getMessage());
        }
    }
    public static void loadProjectData(JspWriter out) {
        Controller.log.info("loadProjectData");
        try {
            /*
             * Show Project List on Screen
             */
            List<model.Project> listLog = util.Facade.getProjectFacade().findAll();
            out.println("<option></option>");
            for (int i = 0; i < listLog.size(); i++) {
                Project a = listLog.get(i);
                out.println("<option value='" + a.getProjectID() + "'>" + a.getName() + "</option>");
            }
            Controller.log.info("loadProjectData finish.");
        } catch (Exception ex) {
            Controller.log.error("Error loadProjectData: " + ex.getMessage());
        }
    }
    public static void loadProjectStatusData(JspWriter out, String id) {
        Controller.log.info("loadProjectStatusData");
        try {
            /*
             * Show Project Status List on Screen
             */
            List<model.Projectstatus> listStatus = util.Facade.getProjectStatusFacade().findAll();
            if("".equals(id))
                out.println("<option selected value=''></option>");
            for (int i = 0; i < listStatus.size(); i++) {
                model.Projectstatus a = listStatus.get(i);
                if(id.equalsIgnoreCase(a.getProjectStatusID())){
                    out.println("<option selected value='" + a.getProjectStatusID() + "'>" + a.getName() + "</option>");
                } else {
                    out.println("<option value='" + a.getProjectStatusID() + "'>" + a.getName() + "</option>");
                }
            }
            Controller.log.info("loadProjectStatusData finish.");
        } catch (Exception ex) {
            Controller.log.error("Error loadProjectStatusData: " + ex.getMessage());
        }
    }
    public static void loadEmployeeData(JspWriter out, String id) {
        Controller.log.info("loadEmployeeData");
        try {
            /*
             * Show Project Status List on Screen
             */
            List<model.Employee> listEmployee = util.Facade.getEmployeeFacade().findAll();
            if("".equals(id)){
                out.println("<option selected value=''></option>");
            }
            for (int i = 0; i < listEmployee.size(); i++) {
                model.Employee a = listEmployee.get(i);
                if(id.equalsIgnoreCase(a.getEmployeeID().toString())){
                    out.println("<option selected value='" + a.getEmployeeID() + "'>" + a.getName() + "</option>");
                } else{
                out.println("<option value='" + a.getEmployeeID() + "'>" + a.getName() + "</option>");
                }
            }
            Controller.log.info("loadEmployeeData finish.");
        } catch (Exception ex) {
            Controller.log.error("Error loadEmployeeData: " + ex.getMessage());
        }
    }
}
